package com.moore.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
public class LogController {

    private static final String LOG_FILE_PATH = "toLog.txt";

    @GetMapping("/api/logs")
    public LogResponse getLogs(
            @RequestParam int page,
            @RequestParam int size,
            @RequestParam(required = false) String sortProp,
            @RequestParam(required = false) String sortOrder,
            @RequestParam(required = false) String searchDate,
            @RequestParam(required = false) String searchTime) throws IOException {

        List<String> allLogs = Files.readAllLines(Paths.get(LOG_FILE_PATH));

        // 根据 searchDate 和 searchTime 过滤日志
        if (searchDate != null && !Objects.equals(searchDate, "")) {
            allLogs = allLogs.stream()
                    .filter(log -> log.startsWith(searchDate))
                    .collect(Collectors.toList());
        }
        if (searchTime != null && !Objects.equals(searchTime, "") ) {
            allLogs = allLogs.stream()
                    .filter(log -> log.contains(" " + searchTime + " "))
                    .collect(Collectors.toList());
        }

        // Sort logs if sortProp and sortOrder are provided
        if (sortProp != null && sortOrder != null) {
            Comparator<String> comparator = Comparator.comparing(log -> {
                String[] parts = log.split(" ");
                switch (sortProp) {
                    case "date":
                        return parts[0];
                    case "time":
                        return parts[1];
                    default:
                        return log;
                }
            });
            if ("descending".equals(sortOrder)) {
                comparator = comparator.reversed();
            }
            allLogs = allLogs.stream().sorted(comparator).collect(Collectors.toList());
        }

        int total = allLogs.size();
        int start = (page - 1) * size;
        int end = Math.min(start + size, total);
        List<String> paginatedLogs = allLogs.subList(start, end);

        return new LogResponse(total, paginatedLogs);
    }

    public static class LogResponse {
        private final int total;
        private final List<String> logs;

        public LogResponse(int total, List<String> logs) {
            this.total = total;
            this.logs = logs;
        }

        public int getTotal() {
            return total;
        }

        public List<String> getLogs() {
            return logs;
        }
    }
}